package com.bangbang.service.impl;

import com.alibaba.fastjson.JSON;
import com.bangbang.pojo.PageEsVO;
import com.bangbang.service.EsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageEsVO select(String names, Integer pageNumber, Integer size) throws IOException {
        PageEsVO pev = new PageEsVO();

//            获取开始位置
        Integer start = (pageNumber - 1) * size;
        // 1.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("tb_course");

        // 2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // (1)查询条件 使用QueryBuilders工具类创建
        // 精确查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("occupation", "警察");
        //多值精确查询
//        TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name", "丰", "吴");
        // 匹配查询
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("cou_name", names);
        //匹配全部查询
//        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        //匹配多个字段查询
//        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("张三", "name","occupation");
        //bool 多条件查询 must(类似and)  mustNot(类似not)  should (类似or)
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        boolQueryBuilder.must(QueryBuilders.matchQuery("name","张三"));
//        boolQueryBuilder.must(QueryBuilders.matchQuery("occupation","法官"));
//        boolQueryBuilder.should(QueryBuilders.matchQuery("occupation","法官"));
//        boolQueryBuilder.should(QueryBuilders.matchQuery("occupation","警察"));
//        boolQueryBuilder.mustNot(QueryBuilders.matchQuery("age",58));
        // (2)其他<可有可无>：（可以参考 SearchSourceBuilder 的字段部分）
        // 设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("cou_name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        // 分页
        searchSourceBuilder.from(start);
        searchSourceBuilder.size(size);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // (3)条件投入
        searchSourceBuilder.query(matchQueryBuilder);

        // 3.添加条件到请求
        searchRequest.source(searchSourceBuilder);

        // 4.客户端查询请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //  总条数
        CountRequest countRequest = new CountRequest();
        countRequest.query(matchQueryBuilder);
        CountResponse count = restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
        System.out.println("总条数:"+count.getCount());
        // 5.查看返回结果
        SearchHits hits = search.getHits();
        System.out.println(JSON.toJSONString(hits));
        System.out.println("=======================");
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {

            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("cou_name");
            if (name != null) {
                Text[] fragments = name.getFragments();
                StringBuilder sb = new StringBuilder();
                for (Text text : fragments) {
                    sb.append(text);
                }
                System.out.println(sb);
                sourceAsMap.put("cou_name",sb.toString());
            }
            list.add(sourceAsMap);
        }
        pev.setList(list);
        pev.setCount(count.getCount());
        return pev;
    }
}
